package com.piesat.quake.business.device.mqtt.writer;

import com.piesat.quake.business.device.mqtt.param.ParseParam;

import io.netty.buffer.ByteBuf;

/**
 * 字符写入器
 *
 * @author Gersy
 * @date 2023/2/6
 * @since 1.0
 */
public class CharWriter implements Writer {
    @Override
    public void write(ByteBuf byteBuf, ParseParam param, Object value) {
        int length = param.getLength();
        byte[] bytes = ((String) value).getBytes();
        byte[] data = null;
        if (bytes.length < length) {
            data = new byte[length];
            System.arraycopy(bytes, 0, data, 0, bytes.length);
        } else if (bytes.length == length) {
            data = bytes;
        } else {
            throw new IllegalArgumentException("字符串超过了设定长度：[" +param.field.getName()+':'+ param.getLength()+']');
        }
        byteBuf.writeBytes(data);
    }
}
